<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data1: { type: Object as () => any, required: true },
    data2: { type: Object as () => any, default: [] },
    data3: { type: Object as () => any, default: [] },
    datax: { type: Object as () => any, required: true },
    dataName: { type: Object as () => any, default: [] },
    title: { type: String, default: '' },
    markLine1: { type: Number, default: 0 },
    markLine2: { type: Number, default: 0 },
    markLine3: { type: Number, default: 0 },
    markLine4: { type: Number, default: 0 },
    isScale: { type: Boolean, default: false },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option = ref<any>({
    legend: {
      data: props.dataName,
      top: props.title == '' ? '0%' : '12%', // 图例位置
    },
    tooltip: {
      trigger: 'item',
      appendToBody: true, // 关键设置
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true, // 让 grid 包含坐标轴文本
    },
    xAxis: {
      type: 'category',
      data: props.datax,
      axisTick: { show: false },
    },
    yAxis: [
      {
        type: 'value',
        name: props.dataName[0] || '',
        splitLine: { show: false },
        scale: props.isScale,
      },
      {
        type: 'value',
        name: props.dataName[1] || '',
        splitLine: { show: false },
        scale: props.isScale,
      },
    ],
    series: [
      {
        name: props.dataName[0],
        type: 'line',
        itemStyle: {
          color: '#5470c6',
        },
        data: props.data1,
        smooth: false,
        yAxisIndex: 0,
      },
    ],
  });

  const initCharts = () => {
    try {
      option.value.series[0].data = props.data1 ?? [];
      if (props.data2.length > 0) {
        option.value.series.push({
          name: props.dataName[1],
          type: 'line',
          itemStyle: {
            color: '#fac858', // 使用橙色表示实际
          },
          data: props.data2,
          smooth: false,
          yAxisIndex: 1,
        });
      }
      if (props.data3.length > 0) {
        option.value.series.push({
          name: props.dataName[2],
          type: 'line',
          data: props.data3,
          itemStyle: {
            color: '#91cc75',
          },
          smooth: false,
        });
      }
      // 统一构建 markLine 数据，分别绑定左右 y 轴对应的序列
      const seriesColorData1 = '#5470c6';
      const seriesColorData2 = '#fac858';
      const markLineLeft: any[] = [];
      const markLineRight: any[] = [];
      if (props.markLine1 && props.markLine1 !== 0) {
        markLineLeft.push({
          yAxis: props.markLine1,
          label: { formatter: '上限', color: seriesColorData1 },
          lineStyle: { color: seriesColorData1, width: 1 },
        });
      }
      if (props.markLine2 && props.markLine2 !== 0) {
        markLineLeft.push({
          yAxis: props.markLine2,
          label: { formatter: '下限', color: seriesColorData1 },
          lineStyle: { color: seriesColorData1, width: 1 },
        });
      }
      if (props.markLine3 && props.markLine3 !== 0) {
        markLineRight.push({
          yAxis: props.markLine3,
          label: { formatter: '上限', color: seriesColorData2 },
          lineStyle: { color: seriesColorData2, width: 1 },
        });
      }
      if (props.markLine4 && props.markLine4 !== 0) {
        markLineRight.push({
          yAxis: props.markLine4,
          label: { formatter: '下限', color: seriesColorData2 },
          lineStyle: { color: seriesColorData2, width: 1 },
        });
      }
      if (markLineLeft.length > 0) {
        option.value.series[0].markLine = { symbol: 'none', data: markLineLeft } as any;

        // 当有左Y轴标记线时，手动设置左Y轴范围以保持空隙
        const leftMarkValues = markLineLeft.map((item) => item.yAxis).filter((val) => val !== undefined);
        const leftDataValues = props.data1 || [];

        if (leftMarkValues.length > 0 && leftDataValues.length > 0) {
          const minMark = Math.min(...leftMarkValues);
          const maxMark = Math.max(...leftMarkValues);
          const minData = Math.min(...leftDataValues);
          const maxData = Math.max(...leftDataValues);

          // 设置左Y轴范围，在标记线和数据之间留出空隙
          const padding = Math.max((maxMark - minMark) * 0.1, (maxData - minData) * 0.1);
          option.value.yAxis[0].min = (Math.min(minMark, minData) - padding).toFixed(2);
          option.value.yAxis[0].max = (Math.max(maxMark, maxData) + padding).toFixed(2);
        }
      }

      if (option.value.series[1] && markLineRight.length > 0) {
        option.value.series[1].markLine = { symbol: 'none', data: markLineRight } as any;

        // 当有右Y轴标记线时，手动设置右Y轴范围以保持空隙
        const rightMarkValues = markLineRight.map((item) => item.yAxis).filter((val) => val !== undefined);
        const rightDataValues = props.data2 || [];

        if (rightMarkValues.length > 0 && rightDataValues.length > 0) {
          const minMark = Math.min(...rightMarkValues);
          const maxMark = Math.max(...rightMarkValues);
          const minData = Math.min(...rightDataValues);
          const maxData = Math.max(...rightDataValues);

          // 设置右Y轴范围，在标记线和数据之间留出空隙
          const padding = Math.max((maxMark - minMark) * 0.1, (maxData - minData) * 0.1);
          option.value.yAxis[1].min = (Math.min(minMark, minData) - padding).toFixed(2);
          option.value.yAxis[1].max = (Math.max(maxMark, maxData) + padding).toFixed(2);
        }
      }
      option.value.xAxis.data = props.datax ?? [];
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    // 重建 series，确保顺序与 yAxisIndex 正确
    option.value.series = [
      {
        name: props.dataName[0],
        type: 'line',
        itemStyle: { color: '#5470c6' },
        data: props.data1 ?? [],
        smooth: false,
        yAxisIndex: 0,
      },
    ];
    if (props.data2.length > 0) {
      option.value.series.push({
        name: props.dataName[1],
        type: 'line',
        itemStyle: { color: '#fac858' },
        data: props.data2,
        smooth: false,
        yAxisIndex: 1,
      });
    }
    if (props.data3.length > 0) {
      option.value.series.push({
        name: props.dataName[2],
        type: 'bar',
        data: props.data3,
        itemStyle: {
          color: '#91cc75',
        },
        smooth: false,
      });
    }
    // 同步 markLine 到更新逻辑
    const seriesColorData1 = '#5470c6';
    const seriesColorData2 = '#fac858';
    const markLineLeft: any[] = [];
    const markLineRight: any[] = [];
    if (props.markLine1 && props.markLine1 !== 0)
      markLineLeft.push({
        yAxis: props.markLine1,
        label: { formatter: '上限', color: seriesColorData1 },
        lineStyle: { color: seriesColorData1, width: 1 },
      });
    if (props.markLine2 && props.markLine2 !== 0)
      markLineLeft.push({
        yAxis: props.markLine2,
        label: { formatter: '下限', color: seriesColorData1 },
        lineStyle: { color: seriesColorData1, width: 1 },
      });
    if (props.markLine3 && props.markLine3 !== 0)
      markLineRight.push({
        yAxis: props.markLine3,
        label: { formatter: '上限', color: seriesColorData2 },
        lineStyle: { color: seriesColorData2, width: 1 },
      });
    if (props.markLine4 && props.markLine4 !== 0)
      markLineRight.push({
        yAxis: props.markLine4,
        label: { formatter: '下限', color: seriesColorData2 },
        lineStyle: { color: seriesColorData2, width: 1 },
      });

    // 清理旧 markLine
    if (option.value.series[0].markLine) delete option.value.series[0].markLine;
    if (option.value.series[1] && option.value.series[1].markLine) delete option.value.series[1].markLine;

    if (markLineLeft.length > 0) {
      option.value.series[0].markLine = { symbol: 'none', data: markLineLeft } as any;

      // 当有左Y轴标记线时，手动设置左Y轴范围以保持空隙
      const leftMarkValues = markLineLeft.map((item) => item.yAxis).filter((val) => val !== undefined);
      const leftDataValues = props.data1 || [];

      if (leftMarkValues.length > 0 && leftDataValues.length > 0) {
        const minMark = Math.min(...leftMarkValues);
        const maxMark = Math.max(...leftMarkValues);
        const minData = Math.min(...leftDataValues);
        const maxData = Math.max(...leftDataValues);

        // 设置左Y轴范围，在标记线和数据之间留出空隙
        const padding = Math.max((maxMark - minMark) * 0.1, (maxData - minData) * 0.1);
        option.value.yAxis[0].min = (Math.min(minMark, minData) - padding).toFixed(2);
        option.value.yAxis[0].max = (Math.max(maxMark, maxData) + padding).toFixed(2);
      }
    }

    if (option.value.series[1] && markLineRight.length > 0) {
      option.value.series[1].markLine = { symbol: 'none', data: markLineRight } as any;

      // 当有右Y轴标记线时，手动设置右Y轴范围以保持空隙
      const rightMarkValues = markLineRight.map((item) => item.yAxis).filter((val) => val !== undefined);
      const rightDataValues = props.data2 || [];

      if (rightMarkValues.length > 0 && rightDataValues.length > 0) {
        const minMark = Math.min(...rightMarkValues);
        const maxMark = Math.max(...rightMarkValues);
        const minData = Math.min(...rightDataValues);
        const maxData = Math.max(...rightDataValues);

        // 设置右Y轴范围，在标记线和数据之间留出空隙
        const padding = Math.max((maxMark - minMark) * 0.1, (maxData - minData) * 0.1);
        option.value.yAxis[1].min = (Math.min(minMark, minData) - padding).toFixed(2);
        option.value.yAxis[1].max = (Math.max(maxMark, maxData) + padding).toFixed(2);
      }
    }

    option.value.xAxis.data = props.datax ?? [];
    chartInstance?.setOption(option.value, true);
    chartInstance?.resize();
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', () => chartInstance?.resize());
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.data1],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
